package cn.zyq.demo.service.sys.impl;


import cn.zyq.demo.beans.sys.SysAdmin;
import cn.zyq.demo.beans.sys.SysRole;
import cn.zyq.demo.service.sys.SysMenuService;
import cn.zyq.demo.service.sys.SysPermissionService;
import cn.zyq.demo.service.sys.SysRoleService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author ruoyi
 */
@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysMenuService menuService;

    /**
     * 获取角色数据权限
     *
     * @param admin 用户信息
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission(SysAdmin admin) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (admin.isAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(admin.getSysAdminID()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param admin 用户信息
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(SysAdmin admin) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (admin.isAdmin()) {
            perms.add("*:*:*");
        } else {
            List<SysRole> roles = admin.getRoles();
            if (CollectionUtils.isNotEmpty(roles)) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles) {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getSysRoleID());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(admin.getSysAdminID()));
            }
        }
        return perms;
    }
}
